package com.atguigu.spzx.cloud.user.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.atguigu.spzx.cloud.user.entity.Order;
import com.atguigu.spzx.cloud.user.entity.User;
import com.atguigu.spzx.cloud.user.fegin.OrderFeignClient;
import com.atguigu.spzx.cloud.user.properties.ErgouziProperties;
import com.atguigu.spzx.cloud.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Random;


@EnableConfigurationProperties(ErgouziProperties.class) //ErgouziProperties加入到ioc容器  【懒汉】
@RestController
@RefreshScope //@Value读取配置中心的配置的时候，支持 热更新
@RequestMapping(value = "/api/user")
public class UserController {


    @Value("${zwf.name:default}")
    private String zwfName;

    @Autowired
    private ErgouziProperties ergouziProperties;

    @Autowired
    private UserService userService ;

    @Autowired
    private OrderFeignClient orderFeignClient;


    @SentinelResource("hot")
    @GetMapping(value = "/findUserByUserId/{userId}")
    public User findUserByUserId(@PathVariable(value = "userId") Long userId , @RequestHeader(required = false) String xxxxx) {

        Random random = new Random();
        int i = random.nextInt(10);
        if (i > 4){
            throw  new RuntimeException("报错啦啊啊！！" + i);
        }
        System.out.println("正常执行！！！");
        return userService.findUserByUserId(userId) ;
    }


    // 修改用户数据端点
    @GetMapping(value = "/updateUserById")
    public String updateUserById() {
        return "修改用户数据成功";
    }


    //todo: 保存单条user数据  post  /api/user/save/one {user的属性,orderList:[{},{},{}]} -> boolean
    @PostMapping("save/one")
    public boolean saveUser(@RequestBody User user){
        //1.将User数据保存
        boolean save = userService.save(user);
        Long id = user.getId(); //mybatis-plus自动回显
        //2.将User的id -> order userId
//        List<Order> orderList = user.getOrderList();
//        for (Order order : orderList) {
//            order.setUserId(id);
//        }
        user.getOrderList().forEach(order -> order.setUserId(id));
        //3.远程调用order保存集合
        boolean orderServiceResult = orderFeignClient.saveBatch(user.getOrderList());
        //4.返回结果
        return save  && orderServiceResult;
    }

    @GetMapping(value = "/save")
    public String save() {
        userService.queryUsers();
        System.out.println("保存用户");
        return "订单保存成功" ;
    }

    @GetMapping(value = "/query")
    public String query() {
        userService.queryUsers();
        System.out.println("查询用户");
        return "查询用户成功" ;
    }


}